<template>
  <div class="main-card">
    <el-card class="box-card">
      <template #header>
        <span>{{ title }}</span>
      </template>
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="basic">
          <basic-info-form ref="basicInfo"/>
        </el-tab-pane>
        <el-tab-pane label="字段信息" name="cloum">
          <el-table ref="dragTable" :data="cloumns" row-key="columnId" :max-height="tableHeight">
            <el-table-column label="序号" type="index" class-name="allowDrag" />
            <el-table-column label="字段列名" prop="columnName" :show-overflow-tooltip="true" width="120px"/>
            <el-table-column label="字段描述" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.columnComment"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="物理类型" prop="columnType" :show-overflow-tooltip="true" width="120px"/>
            <el-table-column label="Java类型" width="120px">
              <template #default="scope">
                <el-select v-model="scope.row.javaType">
                  <el-option label="Long" value="Long" />
                  <el-option label="String" value="String" />
                  <el-option label="Integer" value="Integer" />
                  <el-option label="Double" value="Double" />
                  <el-option label="BigDecimal" value="BigDecimal" />
                  <el-option label="Date" value="Date" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="java属性" width="150px">
              <template #default="scope">
                <el-input v-model="scope.row.javaField"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="插入">
              <template #default="scope">
                <el-checkbox true-label="1" v-model="scope.row.isInsert"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="编辑">
              <template #default="scope">
                <el-checkbox true-label="1" v-model="scope.row.isEdit"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="列表">
              <template #default="scope">
                <el-checkbox true-label="1" v-model="scope.row.isList"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="查询">
              <template #default="scope">
                <el-checkbox true-label="1" v-model="scope.row.isQuery"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="查询方式" width="150px">
              <template #default="scope">
                <el-select v-model="scope.row.BaseQueryType">
                  <el-option label="=" value="EQ" />
                  <el-option label="!=" value="NE" />
                  <el-option label=">" value="GT" />
                  <el-option label=">=" value="GTE" />
                  <el-option label="<" value="LT" />
                  <el-option label="<=" value="LTE" />
                  <el-option label="LIKE" value="LIKE" />
                  <el-option label="BETWEEN" value="BETWEEN" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="必填">
              <template #default="scope">
                <el-checkbox true-label="1" v-model="scope.row.isRequired"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="显示类型" width="120px">
              <template #default="scope">
                <el-select v-model="scope.row.htmlType">
                  <el-option label="文本框" value="input" />
                  <el-option label="文本域" value="textarea" />
                  <el-option label="下拉框" value="select" />
                  <el-option label="单选框" value="radio" />
                  <el-option label="复选框" value="checkbox" />
                  <el-option label="日期控件" value="datetime" />
                  <el-option label="富文本控件" value="editor" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="字典类型" width="150px">
              <template #default="scope">
                <el-select v-model="scope.row.dictType" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="dict in dictOptions"
                    :key="dict.dictType"
                    :label="dict.dictName"
                    :value="dict.dictType">
                    <span style="float: left">{{ dict.dictName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="生成信息" name="genInfo">
          <gen-info-form ref="genInfo"/>
        </el-tab-pane>
      </el-tabs>
      <el-form label-width="100px">
        <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="close()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { reactive, toRefs, ref, onMounted, defineComponent } from 'vue'
import BasicInfoForm from './components/BasicInfoForm.vue'
import GenInfoForm from './components/GenInfoForm.vue'
import Sortable from 'sortablejs'
import { ElMessage } from 'element-plus'
import { DictData } from '@/store/modules/system/dictData'
import { StateType as GenCodeStateType, GenTableColumn } from '@/store/modules/system/genCode'

interface DataType {
  activeName: string;
  cloumns: Array<GenTableColumn>;
  tableHeight: string;
  dictOptions: Array<DictData>;
}

export default defineComponent({
  components: { BasicInfoForm, GenInfoForm },
  name: 'EditTable',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const title = route.meta.title
    const store = useStore<{genCode: GenCodeStateType}>()
    const data = reactive<DataType>({
      activeName: 'cloum',
      cloumns: [],
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + 'px',
      dictOptions: []
    })
    const dragTable = ref<HTMLHtmlElement>()
    const basicInfo = ref<HTMLHtmlElement>()
    const genInfo = ref<HTMLHtmlElement>()
    onMounted(() => {
      const el = (dragTable.value as any).$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      Sortable.create(el, {
        handle: '.allowDrag',
        onEnd: (evt: any) => {
          const targetRow = data.cloumns.splice(evt.oldIndex, 1)[0]
          data.cloumns.splice(evt.newIndex, 0, targetRow)
          for (const index in data.cloumns) {
            data.cloumns[index].sort = parseInt(index) + 1
          }
        }
      })
    })
    const getGenTable = () => {
      const id = route.params.tableId
      store.dispatch('genCode/getGenTable', id).then((res) => {
        data.cloumns = res.data.rows
        store.commit('genCode/SET_INFO', res.data.info)
        store.commit('genCode/SET_TABLES', res.data.tables)
      })
    }
    getGenTable()
    const getDictOptions = () => {
      store.dispatch('dictType/optionSelect').then(res => {
        data.dictOptions = res.data
      })
    }
    getDictOptions()
    const close = () => {
      store.dispatch('tagsView/delView', route)
      router.push({ name: 'GenCode', query: { t: Date.now() } })
    }
    const getFormPromise = (form: HTMLElement) => {
      return new Promise(resolve => {
        (form as any).validate((res: boolean) => {
          resolve(res)
        })
      })
    }
    const submitForm = () => {
      const basicForm = (basicInfo.value as any).$refs.basicInfoForm
      const genForm = (genInfo.value as any).$refs.genInfoForm
      Promise.all([basicForm, genForm].map(getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item)
        if (validateResult) {
          const genTable = Object.assign({}, basicForm.model, genForm.model)
          genTable.columns = data.cloumns
          genTable.params = {
            treeCode: genTable.treeCode,
            treeName: genTable.treeName,
            treeParentCode: genTable.treeParentCode,
            parentMenuId: genTable.parentMenuId
          }
          store.dispatch('genCode/updateGenTable', genTable).then(res => {
            ElMessage({
              message: res.msg,
              type: 'success'
            })
            if (res.code === 200) {
              close()
            }
          })
        } else {
          ElMessage({
            message: '表单校验未通过，请重新检查提交内容',
            type: 'error'
          })
        }
      })
    }
    return {
      title,
      basicInfo,
      genInfo,
      dragTable,
      submitForm,
      close,
      ...toRefs(data)
    }
  }
})
</script>
